<template>
  <div class="admin-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="240px" class="sidebar">
        <div class="logo">
          <h3>视频管理系统</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-dark"
          router
        >
          <el-menu-item index="/dashboard">
            <el-icon><Document /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          <el-menu-item index="/categories">
            <el-icon><Menu /></el-icon>
            <span>视频类别管理</span>
          </el-menu-item>
          <el-menu-item index="/video-types">
            <el-icon><VideoCamera /></el-icon>
            <span>视频类型管理</span>
          </el-menu-item>
          <el-menu-item index="/videos">
            <el-icon><VideoPlay /></el-icon>
            <span>视频管理</span>
          </el-menu-item>
          <el-menu-item index="/comments">
            <el-icon><ChatRound /></el-icon>
            <span>评论管理</span>
          </el-menu-item>
          <el-menu-item index="/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <span>管理员控制台</span>
          </div>
          <div class="header-right">
            <span class="user-info">{{ userInfo.username }}</span>
            <el-button type="text" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </el-header>

        <!-- 内容区 -->
        <el-main class="main-content">
          <div class="management-content">
            <h2>视频类别管理</h2>
            <div class="section-title">管理现有的分类目录</div>
            
            <div class="search-bar">
              <el-input
                v-model="searchQuery"
                placeholder="搜索类别名称或描述"
                prefix-icon="el-icon-search"
                style="width: 400px;"
              ></el-input>
              <el-button type="primary" @click="handleAddCategory">
                <el-icon><Plus /></el-icon>
                添加类别
              </el-button>
            </div>

            <!-- 加载状态 -->
            <el-skeleton v-if="loading" :rows="8" animated />
            
            <!-- 分类列表 -->
            <div v-else class="categories-grid">
              <el-card
                v-for="category in filteredCategories"
                :key="category.id"
                class="category-card"
                :body-style="{ padding: '20px' }"
              >
                <div class="category-header">
                  <div class="category-icon">
                    <el-icon :size="24"><component :is="getCategoryIcon(category.icon)"></component></el-icon>
                  </div>
                  <div class="category-title">
                    <h3>{{ safeGetProp(category, 'name', '未命名类别') }}</h3>
                  <div class="video-count">
                    {{ safeGetProp(category, 'video_count', 0) }} 个视频
                  </div>
                  </div>
                  <el-dropdown trigger="click" @click.stop>
                    <el-button type="text" size="small" class="menu-button">
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleEditCategory(category)" :disabled="false">编辑</el-dropdown-item>
                        <el-dropdown-item @click="handleToggleStatus(category)">
                          {{ category.status === 1 ? '禁用' : '启用' }}
                        </el-dropdown-item>
                        <el-dropdown-item @click="handleDeleteCategory(category)" danger :disabled="false">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="category-description">
                  {{ safeGetProp(category, 'description', '') }}
                </div>
                <div class="category-footer">
                  <span class="created-date">{{ formatDate(safeGetProp(category, 'created_at', new Date().toISOString())) }}</span>
                  <span class="status-label" :class="category.status === 1 ? 'status-enabled' : 'status-disabled'">
                    {{ category.status === 1 ? '启用' : '禁用' }}
                  </span>
                  
                </div>
              </el-card>
              
              <!-- 空状态 -->
              <div v-if="categories.length === 0" class="empty-state">
                <el-empty description="暂无类别数据" />
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加/编辑类别对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingCategory.id ? '编辑类别' : '添加类别'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="editingCategory"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="editingCategory.name" placeholder="请输入类别名称" />
        </el-form-item>
        <el-form-item label="类别别名" prop="alias">
          <el-input v-model="editingCategory.alias" placeholder="请输入类别别名（用于URL）" />
        </el-form-item>
        <el-form-item label="类别图标" prop="icon">
          <el-select v-model="editingCategory.icon" placeholder="选择类别图标">
            <el-option label="Star" value="Star" />
            <el-option label="HomeFilled" value="HomeFilled" />
            <el-option label="Monitor" value="Monitor" />
            <el-option label="VideoCamera" value="VideoCamera" />
            <el-option label="Camera" value="Camera" />
          </el-select>
        </el-form-item>
        <el-form-item label="类别描述" prop="description">
          <el-input
            v-model="editingCategory.description"
            placeholder="请输入类别描述"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="父类别" prop="parent_id">
          <el-select v-model="editingCategory.parent_id" placeholder="选择父类别（可选）" clearable>
            <el-option value="" label="无" />
            <el-option
              v-for="cat in parentCategories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序顺序" prop="sort_order">
          <el-input-number v-model="editingCategory.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="editingCategory.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Document, User, Menu, VideoPlay, ChatRound, Setting, SwitchButton, Plus, More, Star, HomeFilled, Monitor, VideoCamera, Camera } from '@element-plus/icons-vue';
import { categoryService } from '../api/categoryService';

interface Category {
  id: number;
  name: string;
  alias: string;
  icon: string;
  description: string;
  parent_id: number | null;
  level: number;
  sort_order: number;
  video_count: number;
  status: number;
  created_at: string;
  updated_at: string;
}

const router = useRouter();
const userInfo = ref({ username: '', nickname: '', role: '' });
const searchQuery = ref('');
const categories = ref<Category[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const categoryFormRef = ref<FormInstance>();

// 编辑中的类别
const editingCategory = reactive<Partial<Category>>({
  id: undefined,
  name: '',
  alias: '',
  icon: 'Star',
  description: '',
  parent_id: null,
  level: 1,
  sort_order: 0,
  status: 1
});

// 表单验证规则
const categoryRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入类别名称', trigger: 'blur' },
    { min: 1, max: 50, message: '类别名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  alias: [
    { required: true, message: '请输入类别别名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '别名只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ]
});

const activeMenu = computed(() => {
  return window.location.pathname;
});

const filteredCategories = computed(() => {
  if (!searchQuery.value) return categories.value;
  
  const query = searchQuery.value.toLowerCase();
  return categories.value.filter(category => 
    category.name.toLowerCase().includes(query) || 
    category.description.toLowerCase().includes(query)
  );
});

// 获取父类别列表（排除当前编辑的类别）
const parentCategories = computed(() => {
  return categories.value.filter(cat => !editingCategory.id || cat.id !== editingCategory.id);
});

const iconMap = {
  'Star': Star,
  'HomeFilled': HomeFilled,
  'Monitor': Monitor,
  'VideoCamera': VideoCamera,
  'Camera': Camera
};

/**
 * 获取类别图标组件
 * @param iconName 图标名称
 * @returns 图标组件
 */
const getCategoryIcon = (iconName: string) => {
  return iconMap[iconName as keyof typeof iconMap] || Star;
};

// 安全获取对象属性的函数在文件底部定义

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString);
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return '无效日期';
    }
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit' 
    });
  } catch (error) {
    return '无效日期';
  }
};

/**
 * 初始化用户数据
 */
const initData = () => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    userInfo.value = JSON.parse(userStr);
  }
};

/**
 * 加载所有类别数据
 */
const loadCategories = async () => {
  loading.value = true;
  try {
    const response = await categoryService.getAllCategories();
    console.log('API响应原始数据:', response);
    
    if (response.code === 200) {
      // 确保data是数组
      let dataToProcess = response.data;
      if (!Array.isArray(dataToProcess)) {
        console.warn('数据不是数组格式，尝试解析:', dataToProcess);
        // 如果是字符串，再次尝试解析
        if (typeof dataToProcess === 'string') {
          try {
            dataToProcess = JSON.parse(dataToProcess);
          } catch (e) {
            console.error('解析失败:', e);
            ElMessage.error('数据格式错误');
            loading.value = false;
            return;
          }
        }
        // 如果还不是数组，转为数组
        if (!Array.isArray(dataToProcess)) {
          dataToProcess = [dataToProcess];
        }
      }
      
      console.log('原始类别数据:', dataToProcess);
      
      // 处理每个类别对象，确保属性正确
        categories.value = dataToProcess.map((category: any) => {
          // 创建清理后的类别对象
          const cleanedCategory: Category = {
            id: typeof category.id === 'number' ? category.id : 0,
            name: parseJsonValue(category.name, '未命名类别'),
            alias: parseJsonValue(category.alias, ''),
            icon: parseJsonValue(category.icon, 'Star'),
            description: parseJsonValue(category.description, ''),
            parent_id: category.parent_id || null,
            level: typeof category.level === 'number' ? category.level : 1,
            sort_order: typeof category.sort_order === 'number' ? category.sort_order : 0,
            video_count: typeof category.video_count === 'number' ? category.video_count : 
                         (typeof category.video_count === 'string' ? parseInt(category.video_count) || 0 : 0),
            status: typeof category.status === 'number' ? category.status : 
                   (typeof category.status === 'string' ? parseInt(category.status) || 1 : 1),
            created_at: typeof category.created_at === 'string' ? category.created_at : '',
            updated_at: typeof category.updated_at === 'string' ? category.updated_at : ''
          };
          
          return cleanedCategory;
        });
      
      console.log('处理后的类别数据:', categories.value);
    } else {
      ElMessage.error(response.message || '获取类别失败');
    }
  } catch (error) {
    console.error('获取类别失败:', error);
    ElMessage.error('获取类别失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 处理可能是JSON字符串的值，确保正确解析并返回文本内容
 * @param value 原始值
 * @param defaultValue 默认值
 * @returns 清理后的值
 */
const parseJsonValue = (value: any, defaultValue: string): string => {
  if (!value && value !== 0) return defaultValue;
  
  try {
    // 如果已经是字符串，直接处理
    let strValue = typeof value === 'string' ? value : String(value);
    
    // 移除多余空格
    strValue = strValue.trim();
    
    // 检查是否为JSON格式字符串
    if (strValue.startsWith('{') && strValue.endsWith('}')) {
      try {
        const parsed = JSON.parse(strValue);
        if (typeof parsed === 'object' && parsed !== null) {
          // 优先返回name属性
          if (parsed.name) return String(parsed.name);
          // 其次返回第一个非空值
          for (const key in parsed) {
            if (parsed[key]) {
              return String(parsed[key]);
            }
          }
        }
      } catch (e) {
        // JSON解析失败，继续处理
      }
    }
    
    // 处理JSON键值对片段，如 "name":"动画" 或 'name':'动画'
    const jsonKeyValuePattern = /["']([^"']+)["']\s*:\s*["']([^"']*)["']/;
    const match = strValue.match(jsonKeyValuePattern);
    if (match && match.length >= 3) {
      // 返回匹配的值部分，确保是string类型
      return match[2] ?? '';
    }
    
    // 移除可能的引号
    strValue = strValue.replace(/^["']|["']$/g, '');
    
    return strValue || defaultValue;
  } catch (error) {
    console.error('处理值失败:', error);
    return defaultValue;
  }
};

/**
 * 安全获取对象属性，处理可能的JSON字符串
 * @param obj 目标对象
 * @param prop 属性名
 * @param defaultValue 默认值
 * @returns 处理后的属性值或默认值
 */
const safeGetProp = (obj: any, prop: string, defaultValue: any) => {
  try {
    // 检查对象和属性是否存在
    if (!obj || typeof obj !== 'object' || !(prop in obj)) {
      return defaultValue;
    }
    
    let value = obj[prop];
    
    // 使用提取函数处理值
    return parseJsonValue(value, defaultValue);
  } catch (error) {
    console.error(`获取属性 ${prop} 失败:`, error);
    return defaultValue;
  }
};

/**
 * 退出登录
 */
const handleLogout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  ElMessage.success('退出登录成功');
  router.push('/login');
};

/**
 * 打开添加类别对话框
 */
const handleAddCategory = () => {
  // 重置表单数据
  Object.assign(editingCategory, {
    id: undefined,
    name: '',
    alias: '',
    icon: 'Star',
    description: '',
    parent_id: null,
    level: 1,
    sort_order: 0,
    status: 1
  });
  dialogVisible.value = true;
};

/**
 * 打开编辑类别对话框
 * @param category 要编辑的类别
 */
const handleEditCategory = (category: Category) => {
  // 复制类别数据到编辑对象
  Object.assign(editingCategory, { ...category });
  dialogVisible.value = true;
};

/**
 * 删除类别（禁用按钮与删除按钮功能相同）
 * @param category 要删除的类别
 */
const handleToggleStatus = async (category: Category) => {
  // 直接调用删除函数，实现禁用即删除的功能
  await handleDeleteCategory(category);
};

/**
 * 删除类别
 * @param category 要删除的类别
 */
const handleDeleteCategory = async (category: Category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除类别 "${category.name}" 吗？\n删除后数据将无法恢复。`, 
      '确认删除', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await categoryService.deleteCategory(category.id);
    if (response.code === 200) {
      const index = categories.value.findIndex(c => c.id === category.id);
      if (index > -1) {
        categories.value.splice(index, 1);
      }
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除类别失败:', error);
      ElMessage.error('删除类别失败，请稍后重试');
    }
  }
};

/**
 * 保存类别（添加或更新）
 */
const handleSaveCategory = async () => {
  if (!categoryFormRef.value) return;
  
  try {
    await categoryFormRef.value.validate();
    
    if (editingCategory.id) {
      // 更新类别
      const response = await categoryService.updateCategory(editingCategory.id, {
        name: editingCategory.name,
        alias: editingCategory.alias,
        icon: editingCategory.icon,
        description: editingCategory.description,
        parent_id: editingCategory.parent_id,
        level: editingCategory.level,
        sort_order: editingCategory.sort_order,
        status: editingCategory.status
      });
      
      if (response.code === 200) {
        // 更新本地数据
        const index = categories.value.findIndex(c => c.id === editingCategory.id);
        if (index > -1) {
          categories.value[index] = response.data;
        }
        ElMessage.success('更新成功');
      } else {
        ElMessage.error(response.message || '更新失败');
      }
    } else {
      // 创建新类别
      const response = await categoryService.createCategory({
        name: editingCategory.name!,
        alias: editingCategory.alias!,
        icon: editingCategory.icon,
        description: editingCategory.description,
        parent_id: editingCategory.parent_id,
        level: editingCategory.level!,
        sort_order: editingCategory.sort_order!
      });
      
      if (response.code === 201) {
        categories.value.push(response.data);
        ElMessage.success('创建成功');
      } else {
        ElMessage.error(response.message || '创建失败');
      }
    }
    
    dialogVisible.value = false;
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('保存类别失败:', error);
      // 表单验证失败不需要额外提示
    }
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
  loadCategories();
});
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  background-color: #1a1a1a;
}

.sidebar {
  background-color: #2a2a2a;
  height: 100vh;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #3a3a3a;
}

.logo h3 {
  color: #ffffff;
  margin: 0;
}

.el-menu-vertical-dark {
  background-color: transparent;
  border-right: none;
}

.el-menu-item {
  color: #cccccc;
  margin: 0 10px;
  border-radius: 4px;
}

.el-menu-item:hover {
  background-color: #3a3a3a;
  color: #ffffff;
}

.el-menu-item.is-active {
  background-color: #409eff;
  color: #ffffff;
}

.header {
  background-color: #2a2a2a;
  color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #3a3a3a;
}

.user-info {
  margin-right: 20px;
  color: #cccccc;
}

.main-content {
  background-color: #1a1a1a;
  padding: 20px;
  overflow: auto;
  min-height: calc(100vh - 60px);
}

.management-content h2 {
  color: #ffffff;
  margin-bottom: 5px;
}

.section-title {
  color: #999999;
  margin-bottom: 20px;
  font-size: 14px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.category-card {
  background-color: #2a2a2a;
  border: none;
  border-radius: 8px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.category-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 15px;
}

.category-icon {
  color: #409eff;
  margin-right: 15px;
}

.category-title {
  flex: 1;
}

.category-title h3 {
    color: #ffffff;
    margin: 0 0 5px 0;
    font-size: 18px;
  }
  
  .menu-button {
    cursor: pointer;
    z-index: 10;
    padding: 5px;
    border-radius: 4px;
  }
  
  .menu-button:hover {
    background-color: rgba(255, 255, 255, 0.1);
  }
  
  /* 确保下拉菜单可点击 */
  :deep(.el-dropdown-menu__item) {
    cursor: pointer;
    user-select: none;
  }
  
  :deep(.el-dropdown-menu__item):hover {
    background-color: #409eff;
    color: #ffffff;
  }

.video-count {
  color: #999999;
  font-size: 14px;
}

.category-description {
  color: #cccccc;
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.category-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #3a3a3a;
}

.created-date {
  color: #999999;
  font-size: 12px;
}

.status-label {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  user-select: none;
  cursor: default;
}

.status-enabled {
  background-color: #67c23a;
  color: #ffffff;
}

.status-disabled {
  background-color: #f56c6c;
  color: #ffffff;
}

.empty-state {
  grid-column: 1 / -1;
  padding: 60px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 确保表单在深色模式下正常显示 */
:deep(.el-dialog__header) {
  background-color: #2a2a2a;
  border-bottom: 1px solid #3a3a3a;
}

:deep(.el-dialog__title) {
  color: #ffffff;
}

:deep(.el-dialog__body) {
  background-color: #2a2a2a;
  color: #cccccc;
}

:deep(.el-dialog__footer) {
  background-color: #2a2a2a;
  border-top: 1px solid #3a3a3a;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: #1a1a1a;
  border-color: #3a3a3a;
}

:deep(.el-input__inner),
:deep(.el-select__placeholder),
:deep(.el-textarea__inner) {
  color: #cccccc;
}

:deep(.el-form-item__label) {
  color: #cccccc;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-textarea__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.1);
}

:deep(.el-switch__core) {
  background-color: #666;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #409eff;
}
</style>